package com.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.ServletHelp;

import net.sf.json.JSONObject;

public class LoginFilter implements Filter{
	

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		request.setCharacterEncoding("utf-8");//针对post提交的转码
        response.setContentType("text/html;charset=utf-8");//针对url提交的乱码处理
		String currentURL = request.getRequestURI();//取得根目录所对应的绝对路径:
		String targetURL = currentURL.substring(currentURL.indexOf("/", 1), currentURL.length());  //截取到当前文件名用于比较
		HttpSession session = request.getSession();
		if (!"/".equals(targetURL)&&!"/Login.jsp".equals(targetURL)&&!"/page/common/sessionError.jsp".equals(targetURL)&&!targetURL.contains("/postLoginAction.action")&&!targetURL.contains("/specialLoginAction.action")&&!targetURL.contains("/registerFrontUserInfor.action")&&!targetURL.contains("/proving_proving.action")) {//判断当前页是否是重定向以后的登录页面页面，如果是就不做session的判断，防止出现死循环
			   if (session == null || session.getAttribute("user") == null) {//*用户登录以后需手动添加session
				   if (targetURL.contains(".action"))
			         {
			           JSONObject res = new JSONObject();
			           res.put("success", Boolean.valueOf(false));
			           res.put("message", "网络连接超时，请重新登录.");
			           res.put("exceptionMsg", "网络连接超时，请重新登录.");
			           ServletHelp.outRequestForJson(request, response, res.toString());
			           return;
			         }
			    response.sendRedirect(request.getContextPath() + "/page/common/sessionError.jsp");//如果session为空表示用户没有登录就重定向到login.jsp页面
//			    System.out.println(request.getContextPath() + "/page/common/sessionError.jsp======");
			    return;
			}
	   }
	   filterChain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
